package com.itheima.bos.web.action;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.itheima.bos.constant.Constants;
import com.itheima.bos.utils.MailUtils;
import com.itheima.bos.utils.SmsDemoUtils;
import com.itheima.bos.web.action.common.BaseAction;
import com.itheima.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/customer")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Action(value="customer_sendSms",results={@Result(name="success",type="json")})
	public String customer_sendSms(){
		final String code = SmsDemoUtils.getNumber();
		final String telephone = model.getTelephone();
		//将验证码放在session中
		ServletActionContext.getRequest().getSession().setAttribute(telephone, code);
		ServletActionContext.getRequest().getSession().setMaxInactiveInterval(1*60);
		//发送短信
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", telephone);
				mapMessage.setString("code", code);
				return mapMessage;
			}
			
		});
		System.out.println("短信成功发送给[" + telephone + "],验证码为:" + code);
		Map<String, String> map = new HashMap<String,String>();
		map.put("code", code);
		ServletActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	//手机验证码
	private String checkCode;
	
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	@Action(value="customer_signUp",results={@Result(name="success",type="redirect",location="../signup-success.html")
											,@Result(name="input",type="redirect",location="../signup.html")})
	public String customer_signUp(){
		String code = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if(checkCode == null || !checkCode.equals(code)){
			return INPUT;
		}
		WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/customerSignUp")
			.type(MediaType.APPLICATION_JSON)
			.post(model);
		String activeCode = RandomStringUtils.randomNumeric(32);
		redisTemplate.opsForValue().set(model.getTelephone(), activeCode, 1, TimeUnit.DAYS);
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activecode=" + activeCode + "'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("bos速运账户激活", content , model.getEmail(),"");
		return SUCCESS;
	}
	
	//邮箱激活码
	private String activeCode;
	
	public void setActivecode(String activeCode) {
		this.activeCode = activeCode;
	}

	@Action(value="customer_activeMail")
	public String customer_activeMail() throws Exception{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		//1 . 判断激活码是否正确
		String activecodeRedis = (String) redisTemplate.opsForValue().get(model.getTelephone());
		if(activeCode == null || !activeCode.equals(activecodeRedis)){
			ServletActionContext.getResponse().getWriter().println("激活码不正确!!!");
			return NONE;
		}
		//2 . 判断激活码是否有效,是否存在重复绑定
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/customerCheckActiveCode?telephone="+model.getTelephone())
				.accept(MediaType.APPLICATION_JSON)
				.type(MediaType.APPLICATION_JSON)
				.get(Customer.class);
		if(customer != null && customer.getType() != 1){
			//3 . 使用webservice激活账户
			WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/customerActive?telephone="+ model.getTelephone())
				.type(MediaType.APPLICATION_JSON)
				.put(null);
			ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
		}else{
			ServletActionContext.getResponse().getWriter().println("已经激活账号,您可以登陆使用了.谢谢!");
		}
		//最后删除redis中的激活码
		redisTemplate.delete(model.getTelephone());
		return NONE;
	}
	
	@Action(value="customer_login",
			results={@Result(name="success",type="redirect",location="../index.html#/myhome"),
					 @Result(name="input",type="redirect",location="../login.html")})
	public String customer_login(){
		String telephone = model.getTelephone();
		String password = model.getPassword();
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/customerLogin?telephone=" + telephone + "&password="+password)
				.type(MediaType.APPLICATION_JSON)
				.accept(MediaType.APPLICATION_JSON)
				.get(Customer.class);
		if(customer == null){
			System.out.println("账号或者密码错误!!");
			return INPUT;
		}
		if(customer.getType() != 1){
			System.out.println("账号未激活!!");
			return INPUT;
		}
		ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
		return SUCCESS;
	}
}
